import os
import redis
import datetime
import configparser


class MyRedis:
    def __init__(self):
        self.config = configparser.ConfigParser()
        config_path = os.path.join(os.path.dirname(__file__), "./../../../config.ini")
        self.config.read(config_path, encoding="utf-8")
        self.redis_is_available, self.redis_cli = self.check_redis_is_available()

    def get_redis(self) -> redis.Redis:
        redis_server = redis.Redis(
            host=self.config.get("REDIS", "HOST"),
            port=int(self.config.get("REDIS", "PORT")),
            password=self.config.get("REDIS", "PASSWORD"),
            db=int(self.config.get("REDIS", "DB"))
        )
        return redis_server

    def check_redis_is_available(self) -> tuple[bool, redis.Redis | None]:
        redis_client: redis.Redis = self.get_redis()
        try:
            redis_client.ping()
            return True, redis_client
        except Exception as e:
            print(f"redis连接出错，无法写入redis: {e}")
        return False, None

    def set_key(self, key: str):
        if self.redis_is_available:
            self.redis_cli.expire(key, 1 * 60 * 60)
            self.redis_cli.set(key, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    def check_key_exist(self, key: str) -> bool:
        if self.redis_is_available:
            return bool(self.redis_cli.exists(key))
        return False

    def del_key(self, key: str):
        if self.redis_is_available:
            self.redis_cli.delete(key)
